<template>
  <div class="log-management">
    <!-- 页面标题和操作按钮 -->
    <div class="page-header">
      <div class="header-left">
        <h1 class="page-title">日志管理</h1>
        <p class="page-description">系统操作日志记录</p>
      </div>
      <div class="header-actions">
        <el-button type="primary" :icon="Download" @click="exportLogs">
          导出日志
        </el-button>
        <el-button :icon="Refresh" @click="refreshLogs">刷新</el-button>
        <el-button :icon="Delete" type="danger" @click="clearLogs">
          清空日志
        </el-button>
      </div>
    </div>

    <!-- 筛选工具栏 -->
    <div class="filter-toolbar">
      <!-- 搜索框 -->
      <div class="search-section">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索日志内容、用户、操作..."
          prefix-icon="Search"
          style="width: 300px;"
          @keyup.enter="handleSearch"
          clearable
        />
        <el-button type="primary" :icon="Search" @click="handleSearch">
          搜索
        </el-button>
      </div>

      <!-- 筛选器 -->
      <div class="filter-section">
        <!-- 时间范围 -->
        <el-date-picker
          v-model="dateRange"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          format="YYYY-MM-DD HH:mm:ss"
          value-format="YYYY-MM-DD HH:mm:ss"
          @change="handleDateRangeChange"
          style="width: 350px;"
        />

        <!-- 用户筛选 -->
        <el-select 
          v-model="filterUser" 
          placeholder="选择用户" 
          style="width: 150px;" 
          clearable
          @change="handleFilterChange"
        >
          <el-option label="全部用户" value="" />
          <el-option 
            v-for="user in userList" 
            :key="user.id" 
            :label="user.name" 
            :value="user.name" 
          />
        </el-select>

        <!-- 操作类型筛选 -->
        <el-select 
          v-model="filterAction" 
          placeholder="操作类型" 
          style="width: 150px;" 
          clearable
          @change="handleFilterChange"
        >
          <el-option label="全部操作" value="" />
          <el-option label="登录系统" value="login" />
          <el-option label="退出登录" value="logout" />
          <el-option label="创建工单" value="create_ticket" />
          <el-option label="编辑工单" value="edit_ticket" />
          <el-option label="删除工单" value="delete_ticket" />
          <el-option label="分配工单" value="assign_ticket" />
          <el-option label="编辑权限" value="edit_permission" />
          <el-option label="创建用户" value="create_user" />
          <el-option label="删除用户" value="delete_user" />
        </el-select>

        <!-- 结果状态筛选 -->
        <el-select 
          v-model="filterResult" 
          placeholder="执行结果" 
          style="width: 120px;" 
          clearable
          @change="handleFilterChange"
        >
          <el-option label="全部结果" value="" />
          <el-option label="成功" value="success" />
          <el-option label="失败" value="failure" />
        </el-select>

        <!-- 重置按钮 -->
        <el-button @click="resetFilters">重置筛选</el-button>
      </div>
    </div>

    <!-- 日志统计卡片 -->
    <div class="log-stats">
      <div class="stat-card">
        <div class="stat-icon total">
          <el-icon><Document /></el-icon>
        </div>
        <div class="stat-content">
          <div class="stat-value">{{ logStats.total }}</div>
          <div class="stat-label">总日志数</div>
        </div>
      </div>

      <div class="stat-card">
        <div class="stat-icon success">
          <el-icon><CircleCheck /></el-icon>
        </div>
        <div class="stat-content">
          <div class="stat-value">{{ logStats.success }}</div>
          <div class="stat-label">成功操作</div>
        </div>
      </div>

      <div class="stat-card">
        <div class="stat-icon failure">
          <el-icon><CircleClose /></el-icon>
        </div>
        <div class="stat-content">
          <div class="stat-value">{{ logStats.failure }}</div>
          <div class="stat-label">失败操作</div>
        </div>
      </div>

      <div class="stat-card">
        <div class="stat-icon today">
          <el-icon><Calendar /></el-icon>
        </div>
        <div class="stat-content">
          <div class="stat-value">{{ logStats.today }}</div>
          <div class="stat-label">今日日志</div>
        </div>
      </div>
    </div>

    <!-- 日志列表表格 -->
    <div class="log-table-container">
      <el-table
        :data="paginatedLogs"
        v-loading="loading"
        stripe
        border
        style="width: 100%"
        :default-sort="{ prop: 'timestamp', order: 'descending' }"
        @selection-change="handleSelectionChange"
      >
        <!-- 选择列 -->
        <el-table-column type="selection" width="50" />
        
        <!-- 时间戳 -->
        <el-table-column prop="timestamp" label="时间" width="180" sortable>
          <template #default="{ row }">
            <div class="timestamp">
              <el-icon><Clock /></el-icon>
              {{ formatDateTime(row.timestamp) }}
            </div>
          </template>
        </el-table-column>
        
        <!-- 用户 -->
        <el-table-column prop="user" label="用户" width="120">
          <template #default="{ row }">
            <div class="user-info">
              <el-avatar :size="24" :src="row.userAvatar">
                {{ row.user.charAt(0) }}
              </el-avatar>
              <span class="user-name">{{ row.user }}</span>
            </div>
          </template>
        </el-table-column>
        
        <!-- 操作动作 -->
        <el-table-column prop="action" label="操作" width="140">
          <template #default="{ row }">
            <el-tag :type="getActionType(row.action)" size="small">
              {{ getActionText(row.action) }}
            </el-tag>
          </template>
        </el-table-column>
        
        <!-- 操作对象 -->
        <el-table-column prop="target" label="操作对象" min-width="200" show-overflow-tooltip>
          <template #default="{ row }">
            <div class="target-info">
              <el-icon><component :is="getTargetIcon(row.action)" /></el-icon>
              <span>{{ row.target }}</span>
            </div>
          </template>
        </el-table-column>
        
        <!-- 执行结果 -->
        <el-table-column prop="result" label="结果" width="100">
          <template #default="{ row }">
            <div class="result-status">
              <el-icon 
                :class="row.result === 'success' ? 'success-icon' : 'failure-icon'"
              >
                <component :is="row.result === 'success' ? 'CircleCheck' : 'CircleClose'" />
              </el-icon>
              <span>{{ row.result === 'success' ? '成功' : '失败' }}</span>
            </div>
          </template>
        </el-table-column>
        
        <!-- IP地址 -->
        <el-table-column prop="ipAddress" label="IP地址" width="140">
          <template #default="{ row }">
            <code class="ip-address">{{ row.ipAddress }}</code>
          </template>
        </el-table-column>
        
        <!-- 详细信息 -->
        <el-table-column prop="details" label="详细信息" min-width="250" show-overflow-tooltip>
          <template #default="{ row }">
            <div class="log-details">
              {{ row.details }}
            </div>
          </template>
        </el-table-column>
        
        <!-- 操作列 -->
        <el-table-column label="操作" width="100" fixed="right">
          <template #default="{ row }">
            <el-button 
              type="primary" 
              :icon="View" 
              size="small" 
              @click="viewLogDetail(row)"
              title="查看详情"
            />
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[20, 50, 100, 200]"
          :total="totalLogs"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 日志详情对话框 -->
    <el-dialog
      v-model="showDetailDialog"
      title="日志详情"
      width="600px"
      :close-on-click-modal="false"
    >
      <div class="log-detail" v-if="selectedLog">
        <div class="detail-section">
          <h4 class="section-title">基本信息</h4>
          <div class="detail-grid">
            <div class="detail-item">
              <label>时间：</label>
              <span>{{ formatDateTime(selectedLog.timestamp) }}</span>
            </div>
            <div class="detail-item">
              <label>用户：</label>
              <span>{{ selectedLog.user }}</span>
            </div>
            <div class="detail-item">
              <label>操作：</label>
              <el-tag :type="getActionType(selectedLog.action)" size="small">
                {{ getActionText(selectedLog.action) }}
              </el-tag>
            </div>
            <div class="detail-item">
              <label>结果：</label>
              <el-tag :type="selectedLog.result === 'success' ? 'success' : 'danger'" size="small">
                {{ selectedLog.result === 'success' ? '成功' : '失败' }}
              </el-tag>
            </div>
            <div class="detail-item">
              <label>IP地址：</label>
              <code>{{ selectedLog.ipAddress }}</code>
            </div>
            <div class="detail-item">
              <label>用户代理：</label>
              <span>{{ selectedLog.userAgent || '未知' }}</span>
            </div>
          </div>
        </div>
        
        <div class="detail-section">
          <h4 class="section-title">操作详情</h4>
          <div class="detail-content">
            <p><strong>操作对象：</strong>{{ selectedLog.target }}</p>
            <p><strong>详细描述：</strong>{{ selectedLog.details }}</p>
            <div v-if="selectedLog.metadata" class="metadata">
              <strong>附加信息：</strong>
              <pre>{{ JSON.stringify(selectedLog.metadata, null, 2) }}</pre>
            </div>
          </div>
        </div>
      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showDetailDialog = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Download, 
  Refresh, 
  Delete, 
  Search, 
  Document, 
  CircleCheck, 
  CircleClose, 
  Calendar, 
  Clock, 
  View,
  Tickets,
  User,
  Lock,
  Setting
} from '@element-plus/icons-vue'

console.log('日志管理组件加载')

// 响应式数据
const loading = ref(false)
const searchKeyword = ref('')
const dateRange = ref([])
const filterUser = ref('')
const filterAction = ref('')
const filterResult = ref('')
const selectedLogs = ref([])
const currentPage = ref(1)
const pageSize = ref(20)
const totalLogs = ref(0)

// 对话框控制
const showDetailDialog = ref(false)
const selectedLog = ref(null)

// 用户列表
const userList = ref([
  { id: 1, name: '系统管理员' },
  { id: 2, name: '张三' },
  { id: 3, name: '李四' },
  { id: 4, name: '王五' },
  { id: 5, name: '赵六' },
  { id: 6, name: '陈七' },
  { id: 7, name: '刘八' },
  { id: 8, name: '周九' },
  { id: 9, name: '吴十' },
  { id: 10, name: '郑管理员' },
  { id: 11, name: '孙技术' },
  { id: 12, name: '何运维' }
])

// 日志统计数据
const logStats = ref({
  total: 2856,
  success: 2634,
  failure: 222,
  today: 127
})

// 日志列表数据
const logList = ref([
  {
    id: 1,
    timestamp: '2025-01-15 16:30:25',
    user: '张三',
    userAvatar: '',
    action: 'create_ticket',
    target: '工单ID：T001 - 系统登录异常',
    result: 'success',
    ipAddress: '192.168.1.100',
    userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
    details: '用户创建了新的工单，优先级：高，分配给：李四',
    metadata: {
      ticketId: 'T001',
      priority: 'high',
      assignee: '李四'
    }
  },
  {
    id: 2,
    timestamp: '2025-01-15 16:25:18',
    user: '李四',
    userAvatar: '',
    action: 'edit_ticket',
    target: '工单ID：T002 - 数据报表导出功能故障',
    result: 'success',
    ipAddress: '192.168.1.101',
    userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
    details: '用户更新了工单状态从"待处理"到"进行中"',
    metadata: {
      ticketId: 'T002',
      oldStatus: 'pending',
      newStatus: 'in-progress'
    }
  },
  {
    id: 3,
    timestamp: '2025-01-15 16:20:42',
    user: '系统管理员',
    userAvatar: '',
    action: 'edit_permission',
    target: '角色：技术支持 - 权限配置',
    result: 'success',
    ipAddress: '192.168.1.10',
    userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
    details: '管理员更新了技术支持角色的工单管理权限',
    metadata: {
      roleId: 3,
      roleName: '技术支持',
      changedPermissions: ['tickets.edit']
    }
  },
  {
    id: 4,
    timestamp: '2025-01-15 16:15:33',
    user: '王五',
    userAvatar: '',
    action: 'login',
    target: '系统登录',
    result: 'failure',
    ipAddress: '192.168.1.102',
    userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
    details: '用户登录失败，原因：密码错误',
    metadata: {
      failureReason: 'invalid_password',
      attemptCount: 3
    }
  },
  {
    id: 5,
    timestamp: '2025-01-15 16:10:15',
    user: '赵六',
    userAvatar: '',
    action: 'delete_ticket',
    target: '工单ID：T005 - 测试工单',
    result: 'success',
    ipAddress: '192.168.1.103',
    userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
    details: '用户删除了测试工单',
    metadata: {
      ticketId: 'T005',
      ticketTitle: '测试工单'
    }
  },
  {
    id: 6,
    timestamp: '2025-01-15 16:05:28',
    user: '张三',
    userAvatar: '',
    action: 'assign_ticket',
    target: '工单ID：T003 - 新用户权限配置需求',
    result: 'success',
    ipAddress: '192.168.1.100',
    userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
    details: '用户将工单分配给王五处理',
    metadata: {
      ticketId: 'T003',
      oldAssignee: null,
      newAssignee: '王五'
    }
  },
  {
    id: 7,
    timestamp: '2025-01-15 16:00:45',
    user: '系统管理员',
    userAvatar: '',
    action: 'create_user',
    target: '用户：新员工001',
    result: 'success',
    ipAddress: '192.168.1.10',
    userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
    details: '管理员创建了新用户账户，角色：普通用户',
    metadata: {
      username: '新员工001',
      role: '普通用户',
      department: '技术部'
    }
  },
  {
    id: 8,
    timestamp: '2025-01-15 15:55:12',
    user: '李四',
    userAvatar: '',
    action: 'logout',
    target: '系统退出',
    result: 'success',
    ipAddress: '192.168.1.101',
    userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
    details: '用户正常退出系统',
    metadata: {
      sessionDuration: '2h 15m'
    }
  },
  {
    id: 9,
    timestamp: '2025-01-15 15:50:33',
    user: '陈七',
    userAvatar: '',
    action: 'login',
    target: '系统登录',
    result: 'success',
    ipAddress: '192.168.1.105',
    userAgent: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36',
    details: '用户成功登录系统',
    metadata: {
      loginMethod: 'password',
      deviceType: 'desktop'
    }
  },
  {
    id: 10,
    timestamp: '2025-01-15 15:45:21',
    user: '郑管理员',
    userAvatar: '',
    action: 'delete_user',
    target: '用户：离职员工002',
    result: 'success',
    ipAddress: '192.168.1.10',
    userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
    details: '管理员删除了离职员工的账户',
    metadata: {
      username: '离职员工002',
      deleteReason: '员工离职',
      department: '市场部'
    }
  },
  {
    id: 11,
    timestamp: '2025-01-15 15:40:18',
    user: '刘八',
    userAvatar: '',
    action: 'create_ticket',
    target: '工单ID：T006 - 网络连接不稳定',
    result: 'success',
    ipAddress: '192.168.1.106',
    userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
    details: '用户创建了网络故障工单，优先级：中',
    metadata: {
      ticketId: 'T006',
      priority: 'medium',
      category: '网络问题'
    }
  },
  {
    id: 12,
    timestamp: '2025-01-15 15:35:42',
    user: '周九',
    userAvatar: '',
    action: 'edit_ticket',
    target: '工单ID：T004 - 打印机驱动安装',
    result: 'failure',
    ipAddress: '192.168.1.107',
    userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
    details: '用户尝试编辑工单失败，权限不足',
    metadata: {
      ticketId: 'T004',
      errorCode: 'PERMISSION_DENIED',
      requiredRole: '技术支持'
    }
  },
  {
    id: 13,
    timestamp: '2025-01-15 15:30:15',
    user: '孙技术',
    userAvatar: '',
    action: 'assign_ticket',
    target: '工单ID：T007 - 软件许可证到期',
    result: 'success',
    ipAddress: '192.168.1.108',
    userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
    details: '技术人员将许可证工单分配给系统管理员',
    metadata: {
      ticketId: 'T007',
      oldAssignee: null,
      newAssignee: '系统管理员'
    }
  },
  {
    id: 14,
    timestamp: '2025-01-15 15:25:33',
    user: '何运维',
    userAvatar: '',
    action: 'edit_permission',
    target: '角色：普通用户 - 权限配置',
    result: 'success',
    ipAddress: '192.168.1.109',
    userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
    details: '运维人员更新了普通用户的查看权限',
    metadata: {
      roleId: 4,
      roleName: '普通用户',
      changedPermissions: ['tickets.view', 'content.view']
    }
  },
  {
    id: 15,
    timestamp: '2025-01-15 15:20:47',
    user: '吴十',
    userAvatar: '',
    action: 'login',
    target: '系统登录',
    result: 'failure',
    ipAddress: '192.168.1.110',
    userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 14_7_1 like Mac OS X) AppleWebKit/605.1.15',
    details: '移动端登录失败，账户被锁定',
    metadata: {
      failureReason: 'account_locked',
      attemptCount: 5,
      deviceType: 'mobile'
    }
  },
  {
    id: 16,
    timestamp: '2025-01-15 15:15:22',
    user: '张三',
    userAvatar: '',
    action: 'create_ticket',
    target: '工单ID：T008 - 邮件服务器配置',
    result: 'success',
    ipAddress: '192.168.1.100',
    userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
    details: '用户创建了邮件服务器配置工单，优先级：高',
    metadata: {
      ticketId: 'T008',
      priority: 'high',
      category: '系统配置'
    }
  },
  {
    id: 17,
    timestamp: '2025-01-15 15:10:38',
    user: '系统管理员',
    userAvatar: '',
    action: 'create_user',
    target: '用户：新员工003',
    result: 'success',
    ipAddress: '192.168.1.10',
    userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
    details: '管理员创建了新用户账户，角色：编辑者',
    metadata: {
      username: '新员工003',
      role: '编辑者',
      department: '产品部'
    }
  },
  {
    id: 18,
    timestamp: '2025-01-15 15:05:14',
    user: '李四',
    userAvatar: '',
    action: 'delete_ticket',
    target: '工单ID：T009 - 重复工单',
    result: 'success',
    ipAddress: '192.168.1.101',
    userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
    details: '用户删除了重复的工单',
    metadata: {
      ticketId: 'T009',
      ticketTitle: '重复工单',
      deleteReason: '重复提交'
    }
  },
  {
    id: 19,
    timestamp: '2025-01-15 15:00:55',
    user: '王五',
    userAvatar: '',
    action: 'edit_ticket',
    target: '工单ID：T010 - 数据库性能优化',
    result: 'success',
    ipAddress: '192.168.1.102',
    userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
    details: '用户更新了工单状态从"进行中"到"已完成"',
    metadata: {
      ticketId: 'T010',
      oldStatus: 'in-progress',
      newStatus: 'completed'
    }
  },
  {
    id: 20,
    timestamp: '2025-01-15 14:55:31',
    user: '赵六',
    userAvatar: '',
    action: 'logout',
    target: '系统退出',
    result: 'success',
    ipAddress: '192.168.1.103',
    userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
    details: '用户正常退出系统',
    metadata: {
      sessionDuration: '1h 45m'
    }
  },
  {
    id: 21,
    timestamp: '2025-01-15 14:50:17',
    user: '陈七',
    userAvatar: '',
    action: 'assign_ticket',
    target: '工单ID：T011 - 防火墙规则更新',
    result: 'success',
    ipAddress: '192.168.1.105',
    userAgent: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36',
    details: '用户将防火墙工单分配给何运维处理',
    metadata: {
      ticketId: 'T011',
      oldAssignee: null,
      newAssignee: '何运维'
    }
  },
  {
    id: 22,
    timestamp: '2025-01-15 14:45:43',
    user: '郑管理员',
    userAvatar: '',
    action: 'edit_permission',
    target: '角色：管理者 - 权限配置',
    result: 'success',
    ipAddress: '192.168.1.10',
    userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
    details: '管理员更新了管理者角色的系统配置权限',
    metadata: {
      roleId: 2,
      roleName: '管理者',
      changedPermissions: ['system.config', 'users.manage']
    }
  },
  {
    id: 23,
    timestamp: '2025-01-15 14:40:28',
    user: '刘八',
    userAvatar: '',
    action: 'create_ticket',
    target: '工单ID：T012 - 备份策略调整',
    result: 'success',
    ipAddress: '192.168.1.106',
    userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
    details: '用户创建了备份策略调整工单，优先级：中',
    metadata: {
      ticketId: 'T012',
      priority: 'medium',
      category: '系统维护'
    }
  },
  {
    id: 24,
    timestamp: '2025-01-15 14:35:12',
    user: '周九',
    userAvatar: '',
    action: 'login',
    target: '系统登录',
    result: 'failure',
    ipAddress: '192.168.1.107',
    userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
    details: '用户登录失败，用户名不存在',
    metadata: {
      failureReason: 'user_not_found',
      attemptCount: 1
    }
  },
  {
    id: 25,
    timestamp: '2025-01-15 14:30:56',
    user: '孙技术',
    userAvatar: '',
    action: 'edit_ticket',
    target: '工单ID：T013 - 监控系统升级',
    result: 'success',
    ipAddress: '192.168.1.108',
    userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
    details: '技术人员更新了监控系统升级工单的进度',
    metadata: {
      ticketId: 'T013',
      progressUpdate: '已完成50%',
      nextStep: '测试环境部署'
    }
  },
  {
    id: 26,
    timestamp: '2025-01-15 14:25:39',
    user: '何运维',
    userAvatar: '',
    action: 'create_user',
    target: '用户：临时账户001',
    result: 'success',
    ipAddress: '192.168.1.109',
    userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
    details: '运维人员创建了临时访问账户',
    metadata: {
      username: '临时账户001',
      role: '访客',
      expiryDate: '2025-01-22'
    }
  },
  {
    id: 27,
    timestamp: '2025-01-15 14:20:21',
    user: '吴十',
    userAvatar: '',
    action: 'delete_ticket',
    target: '工单ID：T014 - 过期工单',
    result: 'failure',
    ipAddress: '192.168.1.110',
    userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 14_7_1 like Mac OS X) AppleWebKit/605.1.15',
    details: '用户尝试删除工单失败，工单已被锁定',
    metadata: {
      ticketId: 'T014',
      errorCode: 'TICKET_LOCKED',
      lockReason: '正在处理中'
    }
  },
  {
    id: 28,
    timestamp: '2025-01-15 14:15:47',
    user: '张三',
    userAvatar: '',
    action: 'assign_ticket',
    target: '工单ID：T015 - 安全补丁部署',
    result: 'success',
    ipAddress: '192.168.1.100',
    userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
    details: '用户将安全补丁工单分配给孙技术处理',
    metadata: {
      ticketId: 'T015',
      oldAssignee: null,
      newAssignee: '孙技术'
    }
  },
  {
    id: 29,
    timestamp: '2025-01-15 14:10:33',
    user: '系统管理员',
    userAvatar: '',
    action: 'edit_permission',
    target: '角色：采集者 - 权限配置',
    result: 'success',
    ipAddress: '192.168.1.10',
    userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
    details: '管理员更新了采集者角色的数据访问权限',
    metadata: {
      roleId: 5,
      roleName: '采集者',
      changedPermissions: ['data.collect', 'data.view']
    }
  },
  {
    id: 30,
    timestamp: '2025-01-15 14:05:18',
    user: '李四',
    userAvatar: '',
    action: 'logout',
    target: '系统退出',
    result: 'success',
    ipAddress: '192.168.1.101',
    userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
    details: '用户正常退出系统',
    metadata: {
      sessionDuration: '3h 20m'
    }
  }
])

// 计算属性：筛选后的日志列表
const filteredLogs = computed(() => {
  let result = logList.value

  // 关键词搜索
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase()
    result = result.filter(log => 
      log.user.toLowerCase().includes(keyword) ||
      log.target.toLowerCase().includes(keyword) ||
      log.details.toLowerCase().includes(keyword) ||
      getActionText(log.action).toLowerCase().includes(keyword)
    )
  }

  // 用户筛选
  if (filterUser.value) {
    result = result.filter(log => log.user === filterUser.value)
  }

  // 操作类型筛选
  if (filterAction.value) {
    result = result.filter(log => log.action === filterAction.value)
  }

  // 结果状态筛选
  if (filterResult.value) {
    result = result.filter(log => log.result === filterResult.value)
  }

  // 时间范围筛选
  if (dateRange.value && dateRange.value.length === 2) {
    const [startTime, endTime] = dateRange.value
    result = result.filter(log => {
      const logTime = new Date(log.timestamp).getTime()
      const start = new Date(startTime).getTime()
      const end = new Date(endTime).getTime()
      return logTime >= start && logTime <= end
    })
  }

  totalLogs.value = result.length
  return result
})

// 计算属性：分页后的日志列表
const paginatedLogs = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredLogs.value.slice(start, end)
})

// 页面初始化
onMounted(() => {
  console.log('日志管理页面初始化')
  initDateRange()
})

// 初始化日期范围（默认不设置时间筛选，显示所有数据）
const initDateRange = () => {
  // 不设置默认时间范围，让所有模拟数据都能显示
  dateRange.value = []
}

// 刷新日志
const refreshLogs = async () => {
  console.log('刷新日志列表')
  loading.value = true
  
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    ElMessage.success('日志列表刷新成功')
  } catch (error) {
    console.error('刷新失败:', error)
    ElMessage.error('刷新失败，请重试')
  } finally {
    loading.value = false
  }
}

// 导出日志
const exportLogs = () => {
  console.log('导出日志')
  
  ElMessageBox.confirm(
    '确定要导出当前筛选条件下的日志吗？',
    '导出确认',
    {
      confirmButtonText: '确定导出',
      cancelButtonText: '取消',
      type: 'info'
    }
  ).then(() => {
    ElMessage.info('正在导出日志...')
    
    // 模拟导出过程
    setTimeout(() => {
      ElMessage.success(`成功导出 ${filteredLogs.value.length} 条日志`)
    }, 2000)
  }).catch(() => {
    console.log('用户取消导出')
  })
}

// 清空日志
const clearLogs = () => {
  console.log('清空日志')
  
  ElMessageBox.confirm(
    '确定要清空所有日志吗？此操作不可恢复！',
    '危险操作确认',
    {
      confirmButtonText: '确定清空',
      cancelButtonText: '取消',
      type: 'error'
    }
  ).then(() => {
    logList.value = []
    logStats.value = {
      total: 0,
      success: 0,
      failure: 0,
      today: 0
    }
    ElMessage.success('日志已清空')
  }).catch(() => {
    console.log('用户取消清空')
  })
}

// 搜索处理
const handleSearch = () => {
  console.log('搜索日志:', searchKeyword.value)
  currentPage.value = 1
}

// 筛选变更处理
const handleFilterChange = () => {
  console.log('筛选条件变更')
  currentPage.value = 1
}

// 日期范围变更处理
const handleDateRangeChange = (dates) => {
  console.log('日期范围变更:', dates)
  currentPage.value = 1
}

// 分页大小变更处理
const handleSizeChange = (newSize) => {
  console.log('分页大小变更:', newSize)
  pageSize.value = newSize
  currentPage.value = 1
}

// 当前页变更处理
const handleCurrentChange = (newPage) => {
  console.log('当前页变更:', newPage)
  currentPage.value = newPage
}

// 重置筛选条件
const resetFilters = () => {
  console.log('重置筛选条件')
  
  searchKeyword.value = ''
  filterUser.value = ''
  filterAction.value = ''
  filterResult.value = ''
  initDateRange()
  currentPage.value = 1
  
  ElMessage.success('筛选条件已重置')
}

// 选择变更处理
const handleSelectionChange = (selection) => {
  selectedLogs.value = selection
  console.log('选中的日志:', selection.map(l => l.id))
}

// 分页处理函数已在上面定义，这里删除重复定义

// 查看日志详情
const viewLogDetail = (log) => {
  console.log('查看日志详情:', log.id)
  selectedLog.value = log
  showDetailDialog.value = true
}

// 工具函数
const formatDateTime = (dateTime) => {
  return new Date(dateTime).toLocaleString('zh-CN')
}

const getActionType = (action) => {
  const types = {
    login: 'success',
    logout: 'info',
    create_ticket: 'primary',
    edit_ticket: 'warning',
    delete_ticket: 'danger',
    assign_ticket: 'info',
    edit_permission: 'warning',
    create_user: 'success',
    delete_user: 'danger'
  }
  return types[action] || 'info'
}

const getActionText = (action) => {
  const texts = {
    login: '登录系统',
    logout: '退出登录',
    create_ticket: '创建工单',
    edit_ticket: '编辑工单',
    delete_ticket: '删除工单',
    assign_ticket: '分配工单',
    edit_permission: '编辑权限',
    create_user: '创建用户',
    delete_user: '删除用户'
  }
  return texts[action] || '未知操作'
}

const getTargetIcon = (action) => {
  const icons = {
    login: 'User',
    logout: 'User',
    create_ticket: 'Tickets',
    edit_ticket: 'Tickets',
    delete_ticket: 'Tickets',
    assign_ticket: 'Tickets',
    edit_permission: 'Lock',
    create_user: 'User',
    delete_user: 'User'
  }
  return icons[action] || 'Document'
}
</script>

<style scoped>
.log-management {
  height: 100%;
  display: flex;
  flex-direction: column;
  gap: 24px;
}

/* 页面标题 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}

.header-left {
  flex: 1;
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  color: #1f2937;
  margin: 0 0 8px 0;
}

.page-description {
  font-size: 14px;
  color: #6b7280;
  margin: 0;
}

.header-actions {
  display: flex;
  gap: 12px;
}

/* 筛选工具栏 */
.filter-toolbar {
  background: #ffffff;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.search-section {
  display: flex;
  gap: 12px;
  align-items: center;
}

.filter-section {
  display: flex;
  gap: 12px;
  align-items: center;
  flex-wrap: wrap;
}

/* 日志统计卡片 */
.log-stats {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
}

.stat-card {
  background: #ffffff;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
  gap: 16px;
  transition: transform 0.2s ease, box-shadow 0.2s ease;
}

.stat-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
}

.stat-icon {
  width: 50px;
  height: 50px;
  border-radius: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  color: white;
}

.stat-icon.total {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.stat-icon.success {
  background: linear-gradient(135deg, #84fab0 0%, #8fd3f4 100%);
}

.stat-icon.failure {
  background: linear-gradient(135deg, #fa709a 0%, #fee140 100%);
}

.stat-icon.today {
  background: linear-gradient(135deg, #a8edea 0%, #fed6e3 100%);
}

.stat-content {
  flex: 1;
}

.stat-value {
  font-size: 24px;
  font-weight: 700;
  color: #1f2937;
  line-height: 1;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 14px;
  color: #6b7280;
}

/* 表格容器 */
.log-table-container {
  flex: 1;
  background: #ffffff;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

/* 表格样式 */
.timestamp {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 13px;
  color: #374151;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.user-name {
  font-size: 13px;
  color: #374151;
}

.target-info {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 13px;
  color: #374151;
}

.result-status {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 13px;
}

.success-icon {
  color: #10b981;
}

.failure-icon {
  color: #ef4444;
}

.ip-address {
  font-family: 'Courier New', monospace;
  font-size: 12px;
  background: #f3f4f6;
  padding: 2px 6px;
  border-radius: 4px;
  color: #374151;
}

.log-details {
  font-size: 13px;
  color: #6b7280;
  line-height: 1.4;
}

/* 分页 */
.pagination-container {
  padding: 16px;
  border-top: 1px solid #e5e7eb;
  display: flex;
  justify-content: center;
}

/* 日志详情对话框 */
.log-detail {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.detail-section {
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  overflow: hidden;
}

.section-title {
  background: #f9fafb;
  padding: 12px 16px;
  margin: 0;
  font-size: 14px;
  font-weight: 600;
  color: #374151;
  border-bottom: 1px solid #e5e7eb;
}

.detail-grid {
  padding: 16px;
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 12px;
}

.detail-item {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
}

.detail-item label {
  font-weight: 500;
  color: #6b7280;
  min-width: 80px;
}

.detail-content {
  padding: 16px;
}

.detail-content p {
  margin: 0 0 12px 0;
  font-size: 14px;
  line-height: 1.5;
}

.metadata {
  margin-top: 16px;
}

.metadata pre {
  background: #f3f4f6;
  padding: 12px;
  border-radius: 6px;
  font-size: 12px;
  overflow-x: auto;
  margin: 8px 0 0 0;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .log-stats {
    grid-template-columns: repeat(2, 1fr);
  }
}

@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    gap: 16px;
  }
  
  .filter-toolbar {
    padding: 16px;
  }
  
  .search-section,
  .filter-section {
    flex-direction: column;
    align-items: stretch;
  }
  
  .log-stats {
    grid-template-columns: 1fr;
  }
  
  .stat-card {
    padding: 16px;
  }
  
  .detail-grid {
    grid-template-columns: 1fr;
  }
}

/* 深色主题适配 */
@media (prefers-color-scheme: dark) {
  .filter-toolbar,
  .stat-card,
  .log-table-container {
    background: #1f2937;
    border: 1px solid #374151;
  }
  
  .page-title,
  .section-title {
    color: #f9fafb;
  }
  
  .page-description {
    color: #d1d5db;
  }
  
  .stat-value {
    color: #f9fafb;
  }
  
  .stat-label {
    color: #9ca3af;
  }
}
</style>
